﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using WebChatServer.Models;

namespace WebChatServer.Controllers
{
    [HttpHeader("Access-Control-Allow-Origin", "*")]
    // [HttpHeader("Access-Control-Allow-Headers", "Content-Type")]
    [HttpHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS")]
    public class ImageController : ApiController
    {
        //
        // GET: /Image/

        IMemberRepository _repository = new MemberRepository();
        public void Options()
        {

        }

        public Byte[] Post(string id)
        {

            //Image img = file;
            string url = "ddd";
            Byte[] array;
            string path = Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "App_Data/Images/"));
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }
            var provider = new MultipartFormDataStreamProvider(path);

            var task = Request.Content.ReadAsMultipartAsync(provider);
            
            task.Wait();
            foreach (var file in provider.BodyPartFileNames)
            {

                if (File.Exists(path + id + ".jpg"))
                    File.Delete(path + id + ".jpg");
                File.Copy(file.Value, path + id + ".jpg");
                url = file.Value;
                array = _repository.GetImage(path + id + ".jpg");
                return array;
            }
            return new byte[0];
        }
    }
}
